package main

import (
	"bytes"
	"fmt"
)

// 如何求相对路径

func main() {
	path1 := "/app/a/b/c/d/new.c"
	path2 := "/app/1/2/test.c"
	fmt.Println(getRelativePath(path1, path2))
}

func getRelativePath(path1, path2 string) string {
	if path1 == "" || path2 == "" {
		return "参数不合法"
	}

	arr1, arr2 := []rune(path1), []rune(path2)
	diff1, diff2 := 0, 0 // 用来指向两个路径中不同目录的起始路径
	len1, len2 := len(arr1), len(arr2)

	var relativePath bytes.Buffer

	i, j := 0, 0

	// 如果目录相同则往后遍历
	for i < len1 && j < len2 {
		if arr1[i] != arr2[j] {
			break
		}
		if arr1[i] == '/' {
			diff1, diff2 = i, j
		}
		i++
		j++
	}

	// 把 path1 非公共目录部分转换为 ../
	diff1++
	for diff1 < len1 {
		if arr1[diff1] == '/' {
			relativePath.WriteString("../")
		}
		diff1++
	}

	// 把 path2 的非公共部分的路径加到后面
	diff2++
	relativePath.WriteString(string(arr2[diff2:]))

	return relativePath.String()
}
